<template>
    <div class="category-container">
      <el-card class="box-card">
        <div class="add">
        <!--    面包屑导航-->
          <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>类目列表</el-breadcrumb-item>
          </el-breadcrumb>
        <el-button
          type="success"
          size="mini"
          round
          @click="appendParentNode"
          :disabled="isSearching"
          :loading="isAdding">
          添加顶级分类
        </el-button>
        </div>
      </el-card>
      <el-card class="box-card" v-loading="isSearching">
        <el-tree
          :data="options"
          accordion
          :props="defaultProps"
          node-key="label"
          @node-click="handleNodeClick"
          :expand-on-click-node="true">
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                type="text"
                size="mini"
                :disabled="isAdding"
                v-show="!(node != null && node.parent !== null && node.parent.parent !== null && node.parent.parent.parent !== null)"
                @click="() => append(data)">
                添加
              </el-button>
              <el-button
                type="text"
                size="mini"
                :disabled="isDeleting"
                @click="() => remove(node, data)">
                删除
              </el-button>
              <el-button
                type="text"
                size="mini"
                v-show="node != null && node.parent !== null && node.parent.parent !== null && node.parent.parent.parent !== null"
                @click="() => check(data)">
                查看
              </el-button>
            </span>
          </span>
          <br>
          <input type="text" style="width: 100%">
        </el-tree>
      </el-card>
      <el-dialog title="所包含规格参数组" :visible.sync="dialogTableVisible" append-to-body  @close="closeForm">
        <el-select v-model="addSpecGroupQuery.name" placeholder="请选择" style="margin-left: 10px" ref="saveTagInput">
          <el-option
            v-for="item in AllspecGroupList"
            :key="item.id"
            :label="item.name"
            :value="item.name"
          >
          </el-option>
        </el-select>
        <el-button  @keyup.enter.native="$event.target.click"
                    @click="handleInputConfirm"
                    style="margin-left: 10px"
                    :disabled="isSearching"
                    :loading="isAdding"
                    type="success"
        >添加
        </el-button>
        <el-table
          :data="specGroupList"
          @expand-change="expandSelect"
          :row-key="getRowKeys"
          :expand-row-keys="expands"
          v-loading="isSearching"
        >
          <el-table-column
            type="expand" width="100px">
<!--            <template slot-scope="scope">-->
            <template slot-scope="scope">
              <el-table
                :data="scope.row.groupParam"
                style="width: 100%">
                <el-table-column
                  prop="name"
                  label="名称"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="unit"
                  label="单位"
                  width="180">
                </el-table-column>
                <el-table-column
                  prop="options"
                  label="可选值">
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
          <el-table-column property="name" label="名称" width="350"></el-table-column>
          <el-table-column
            prop="sourceAsMap.address"
            label="操作">
            <!-- 如果需要自定义表格列模板，则把需要自定义的内容放到 template 里面 -->
            <template slot-scope="scope">
              <el-tooltip class="item" effect="dark" content="删除规格组" placement="top-end">
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  circle
                  :loading="isDeleting"
                  @click="deleteSpecGroup(scope.$index,scope.row.id)"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-dialog>
    </div>
</template>

<script>
import { Message } from 'element-ui'
import { getBrandTree, addCategory, deleteCategoryById } from '@/api/category'
import { deleteSpecGroupById, findSpecGroupByCategoryId, addSpecGroup } from '@/api/spec'
export default {
  name: 'category',
  components: {},
  props: {},
  data () {
    return {
      options: [],
      specGroupList: [], // 单个分类对应的规格组集合
      AllspecGroupList: [], // 可添加规格参数
      expands: [], // 展开行集合
      isSearching: false, // 搜索/加载loading
      isAdding: false, // 添加loading
      isDeleting: false, // 删除loading
      dialogTableVisible: false, // 查看弹框开关
      defaultProps: { // 配置选项，具体看下表
        value: 'value',
        children: 'children', // 指定子树为节点对象的某个属性值
        label: 'label' // 指定节点标签为节点对象的某个属性值
      },
      getRowKeys (row) { // 每行展开关键字
        return row.id
      },
      addSpecGroupQuery: { // 添加规格组参数表单
        name: '',
        categoryId: 0
      },
      category: {
        name: '',
        parentId: ''
      }
    }
  },
  computed: {},
  watch: {},
  created () {
    this.findCategoryTree()
    this.getSpecGroup()
  },
  mounted () {
  },
  methods: {

    // --------------------------------------------------------类目---------------------------------------------------------

    // 添加顶级节点
    async appendParentNode () {
      this.isAdding = true
      // 填写父id
      this.category.parentId = 0

      await this.$prompt('类目名', '添加', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\u4e00-\u9fffa-zA-Z]{0,15}$/,
        inputErrorMessage: '不超过15个字'
      }).then(async ({ value }) => {
        // 填写category_name
        this.category.name = value
        // 发送添加请求
        await addCategory(this.category).then(resp => {
          // 判断响应结果
          if (resp.data.code === 20000) {
            // 响应成功
            // 刷新页面
            this.findCategoryTree()
            // 提示成功信息
            Message({
              type: 'success',
              message: resp.data.message
            })
          } else {
            // 提示错误信息
            Message({
              type: 'warning',
              message: resp.data.message
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消添加'
        })
      })
      this.isAdding = false
    },


    // 添加子节点
    async append (data) {
      this.isAdding = true
      // 填写父id
      this.category.parentId = data.value

      await this.$prompt('类目名', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^[\u4e00-\u9fffa-zA-Z]{0,15}$/,
        inputErrorMessage: '不超过15个字'
      }).then(({ value }) => {
        // 填写category_name
        this.category.name = value
        // 发送添加请求
        addCategory(this.category).then(resp => {
          // 判断响应结果
          if (resp.data.code === 20000) {
            // 响应成功
            // 添加节点
            const newChild = {
              value: resp.data.data.id,
              label: value,
              children: []
            }
            if (!data.children) {
              this.$set(data, 'children', [])
            }
            data.children.push(newChild)
            // 提示成功信息
            Message({
              type: 'success',
              message: resp.data.message
            })
          } else {
            // 提示错误信息
            Message({
              type: 'warning',
              message: resp.data.message
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消添加'
        })
      })
      this.isAdding = false
    },

    // 删除节点
    async remove (node, data) {
      this.isDeleting = true
      await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 发送添加请求
        await deleteCategoryById(data.value).then(resp => {
          // 判断响应结果
          if (resp.data.code === 20000) {
            // 响应成功
            // 删除节点
            const parent = node.parent
            const children = parent.data.children || parent.data
            const index = children.findIndex(d => d.value === data.value)
            children.splice(index, 1)
            // 删除成功信息提示
            Message({
              type: 'success',
              message: resp.data.message
            })
          } else {
            // 提示错误信息
            Message({
              type: 'warning',
              message: resp.data.message
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      this.isDeleting = false
    },


    // 获取树形类目
    async findCategoryTree () {
      this.isSearching = true
      await getBrandTree().then(resp => {
        if (resp.data.code === 20000) {
          this.options = resp.data.data
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
      this.isSearching = false
    },

    // 获取所有顶级规则组供选择
    async getSpecGroup () {
      this.isSearching = true
      await findSpecGroupByCategoryId(0).then(resp => {
        if (resp.data.code === 20000) {
          this.AllspecGroupList = resp.data.data
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
      this.isSearching = false
    },


    // --------------------------------------------------------规格组--------------------------------------------------

    // 添加规格参数组
    async handleInputConfirm () {
      this.isAdding = true
      await addSpecGroup(this.addSpecGroupQuery).then(async resp => {
        if (resp.data.code === 20000) {
          // 更新
          await findSpecGroupByCategoryId(this.addSpecGroupQuery.categoryId).then(resp => {
            if (resp.data.code === 20000) {
              this.specGroupList = resp.data.data
              Message({
                type: 'success',
                message: resp.data.message
              })
            } else {
              Message({
                type: 'warning',
                message: resp.data.message
              })
            }
          })
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      })
      this.isAdding = false
    },


    // 删除规格组
    async deleteSpecGroup (index, specGroupId) {
      this.isDeleting = true
      await deleteSpecGroupById(specGroupId).then(resp => {
        if (resp.data.code === 20000) {
          // 移除该组
          this.specGroupList.splice(index, 1)
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
      this.isDeleting = false
    },

    // 查看分类下规格组
    async check (data) {
      this.isSearching = true
      // console.log(data)
      this.dialogTableVisible = true
      // 赋值当前选中categoryId
      this.addSpecGroupQuery.categoryId = data.value
      // 查询当前分类下所有规格参数组
      await findSpecGroupByCategoryId(data.value).then(resp => {
        if (resp.data.code === 20000) {
          this.specGroupList = resp.data.data
          Message({
            type: 'success',
            message: resp.data.message
          })
        } else {
          Message({
            type: 'warning',
            message: resp.data.message
          })
        }
      }).catch(() => {})
      this.isSearching = false
    },

    // ------------------------------------------其他---------------------------------------------


    // 选中节点
    handleNodeClick (data) {
      // console.log('选中节点' + JSON.stringify(data))
    },


    // 关闭规格参数标签弹窗
    closeForm () {
      // 清空数据
      this.expands = []
      // 关闭loading
      this.isSearching = false
    },

    // 单击某行时展开
    openColumn (row) {
      // 判断是否是点击同一行
      if (this.expands.length !== 0 && this.expands[0] === row.id) {
        // 重复点击同一行，目的是收起这一行
        this.expands = []
      } else {
        // 点击其他行，展开其他行，关闭这一行
        // 先初始化
        this.expands = []
        // 再添加
        this.expands.push(row.id)
      }
    },


    // 展开行变化时触发
    expandSelect (row, expandedRows) {
      var that = this
      // 只展开一行
      if (expandedRows.length) { // 说明展开了
        that.expands = []
        if (row) {
          that.expands.push(row.id) // 只展开当前行id
        }
      } else { // 说明收起了
        that.expands = []
      }
    }


  }
}
</script>

<style scoped lang="less">
  .box-card {
    width: 100%;
    margin-bottom: 10px;
  }
  .el-button--text {
    color: #409EFF;
    background: 0 0;
    padding-left: 0;
    padding-right: 0;
    margin-left: 20px;
  }
  .add {
    height: 35px;
    display: flex;
    justify-content: space-between;
  }
</style>
